package com.fesine.mongodb.fileserver.controller;

import com.fesine.mongodb.fileserver.domain.File;
import com.fesine.mongodb.fileserver.service.FileService;
import com.fesine.mongodb.fileserver.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

/**
 * @description: 文件控制类
 * @author: Fesine
 * @createTime:2017/12/20
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2017/12/20
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
public class FileController {

    @Autowired
    private FileService fileService;

    @Value("${file.server.address}")
    private String fileServerAddress;

    /**
     * 服务器首页返回所有文件列表
     *
     * @param model
     * @return
     */
    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("files", fileService.listFiles());
        return "index";
    }

    /**
     * 获取文件片信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ResponseBody
    public ResponseEntity getFile(@PathVariable String id) {
        File file = fileService.getFileById(id);
        if (file != null) {
            return ResponseEntity
                    .ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; fileName=\"" + file
                            .getName() + "\"")
                    .header(HttpHeaders.CONTENT_TYPE, "application/octet-stream")
                    .header(HttpHeaders.CONTENT_LENGTH, file.getSize() + "")
                    .header("Connection", "close")
                    .body(file.getContent());
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("File was not fount");
        }
    }

    @DeleteMapping("/{id}")
    public String delete(@PathVariable String id){
        fileService.removeFile(id);
        return "redirect:/";
    }

    /**
     * 在线显示文件
     *
     * @param id
     * @return
     */
    @GetMapping("/view/{id}")
    @ResponseBody
    public ResponseEntity viewFile(@PathVariable String id) {
        File file = fileService.getFileById(id);
        if (file != null) {
            return ResponseEntity
                    .ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "fileName=\"" + file.getName() + "\"")
                    .header(HttpHeaders.CONTENT_TYPE, file.getContentType())
                    .header(HttpHeaders.CONTENT_LENGTH, file.getSize() + "")
                    .header("Connection", "close")
                    .body(file.getContent());
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("File was not fount");
        }
    }

    @PostMapping("/")
    public String uploadFile(@RequestParam("file") MultipartFile file, RedirectAttributes
            redirectAttributes) {
        if (StringUtils.isEmpty(file.getOriginalFilename())){
            //重定向处理
            redirectAttributes.addFlashAttribute("message",
                    "请选择一个文件!");
            return "redirect:/";
        }
        try {
            File f = new File(file.getOriginalFilename(), file.getContentType(), file.getSize(), file
                    .getBytes());
            f.setMd5(MD5Util.getMD5(file.getInputStream()));
            fileService.saveFile(f);
        } catch (IOException |NoSuchAlgorithmException e) {
            e.printStackTrace();
            //重定向处理
            redirectAttributes.addFlashAttribute("message",
                    "Your " + file.getOriginalFilename() + " is wrong!");
            return "redirect:/";
        }
        redirectAttributes.addFlashAttribute("message",
                "You successfully uploaded " + file.getOriginalFilename() + "!");

        return "redirect:/";
    }

    /**
     * 上传文件，同时返回文件地址信息
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (StringUtils.isEmpty(file.getOriginalFilename())) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("请选择一个文件!");
        }
        File returnFile = null;
        //localhost:8081
        String viewPath = fileServerAddress+ "/view/";
        try {
            File f = new File(file.getOriginalFilename(), file.getContentType(), file.getSize(), file.getBytes());
            f.setMd5(MD5Util.getMD5(file.getInputStream()));
            returnFile = fileService.saveFile(f);
            returnFile.setPath(viewPath+ f.getId());
            returnFile.setContent(null);
            return ResponseEntity.status(HttpStatus.OK).body(viewPath + f.getId());

        } catch (IOException | NoSuchAlgorithmException ex) {
            ex.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage());
        }
    }
}
